package com.zhao.task.service;

import com.google.common.collect.Maps;
import com.zhao.task.config.TaskConfig;
import com.zhao.task.inter.TaskAction;
import com.zhao.task.utils.TaskProperty;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 开机自启动
 *
 * @author zhao
 * @date 2018-11-07
 */
@Component
@Slf4j
@SuppressWarnings("all")
public class ServerStartedRunner implements CommandLineRunner {

    @Autowired
    private ApplicationContext context;
    
    /**
     * 轮询全局变量
     */
    public static Map<String, TaskService> taskServiceMap=Maps.newHashMap();

    @Override
    public void run(String... args) throws Exception {
        TaskProperty taskProperty=new TaskProperty(context.getEnvironment());
        Map<String, TaskConfig> map=taskProperty.getTaskConfigMap();
        if (map==null||map.isEmpty()){
            return;
        }
        log.info("task开始读取配置文件");
        for (Map.Entry<String,TaskConfig> entry:map.entrySet()){
            TaskAction action=(TaskAction) context.getBean(entry.getKey());
            TaskConfig config=entry.getValue();
            log.info("task读取到轮询配置{}",config);
            TaskService service=new TaskService(config,action);
            taskServiceMap.put(entry.getKey(), service);
            if (config.isAutoStart()){
            	log.info("task轮询配置{}自启动",config.getKey());
                service.start();
            }
        }
    }
}
